<template>
  <div class="login" @keydown.enter="handleSubmit">
    <div class="login-con">
      <Alert type="error" @on-close="alertClose" closable show-icon v-if="showErrorMsg">{{errorMsg}}</Alert>
      <Card :bordered="false">
        <p slot="title">
          <Icon type="log-in"></Icon>
          欢迎登录:AimaoBlog
        </p>
        <div class="form-con">
          <Form ref="loginForm" :model="form" :rules="rules">
            <FormItem prop="userName">
              <Input v-model="form.userName" placeholder="请输入用户名">
              <span slot="prepend">
                                    <Icon :size="16" type="person"></Icon>
                                </span>
              </Input>
            </FormItem>
            <FormItem prop="password">
              <Input type="password" v-model="form.password" placeholder="请输入密码">
              <span slot="prepend">
                                    <Icon :size="14" type="locked"></Icon>
                                </span>
              </Input>
            </FormItem>
            <FormItem>
              <Button @click="handleSubmit" type="primary" long>登录</Button>
            </FormItem>

          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        showErrorMsg: false,
        errorMsg: '',
        form: {
          userName: '',
          password: ''
        },
        rules: {
          userName: [
            {required: true, message: '账号不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      handleSubmit() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            let params = {
              id: this.form.userName,
              pwd: this.form.password
            };
            this.axios.post(this.baseUrl+'/login', this.$qs.stringify(params))
              .then(response => {
                let data = response.data;
                if (data.code != 0) {
                  this.$router.push({name: 'Home'});
                } else {
                  this.showErrorMsg = true;
                  this.errorMsg = data.msg;
                }
              })
              .catch(error => {
                this.showErrorMsg = true;
                this.errorMsg = "未知的异常 :" + error.status;
              })

          } else {
            this.$Message.warning("请输入完整哦!");
          }
        });
      },
      alertClose() {
        this.showErrorMsg = false;
        this.errorMsg = '';
      }
    }
  }
</script>

<style lang="less" scoped>
  @import 'assets/style/login.less';
</style>
